package com.wu.shiro;


import com.alibaba.fastjson.JSON;
import com.wu.base.ApiResponse;
import com.wu.enums.SystemEnum;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.PassThruAuthenticationFilter;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;


public class ShiroAuthFilter extends PassThruAuthenticationFilter {

    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        Subject subject = getSubject(request, response);
        //1.判断是否已认证过
        boolean isAuthenticated = subject.isAuthenticated();
        //没有认证并且没有记住登录
        if (!isAuthenticated) {
//            if (!isAuthenticated && !subject.isRemembered()) {
            return false;
        }
        //刷新 session 失效时间
        Session session = SecurityUtils.getSubject().getSession();
        session.touch();
        //去头去尾部参数
        ShiroHttpServletRequest shiroRequet = (ShiroHttpServletRequest) request;
        String requestUri = shiroRequet.getRequestURI();
        //认证
        boolean isPermitted = subject.isPermitted(requestUri);

        return isPermitted;
    }


    //处理被阻止的请求
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException{
        Subject subject = getSubject(request, response);
        if (subject.getPrincipal() == null) {
            saveRequestAndRedirectToLogin(request, response);
        } else {
            response.setContentType("application/json; charset=utf-8");
            response.getWriter().write(JSON.toJSONString(new ApiResponse(SystemEnum.ACCESS_DENIED)));
        }
        return false;
    }

    @Override
    protected void redirectToLogin(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException {
        // 返回json
        servletResponse.setContentType("application/json; charset=utf-8");
        String json = JSON.toJSONString(new ApiResponse(SystemEnum.INVALID));

        servletResponse.getWriter().write(json);
    }

}

